package models;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

import play.Logger;
import play.data.format.Formats;
import play.data.validation.Constraints;
import play.db.ebean.Model;

import com.avaje.ebean.Ebean;
import com.smartsheet.api.oauth.Token;

/**
 * SmartsheetToken entity managed by Ebean
 */
@Entity 
public class SmartsheetToken extends Model {

    private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue
    @Column(name="smartsheet_token_id", nullable=false, unique=true)
	public Long smartsheetTokenId;
    
    @Constraints.Required
    @Column(nullable=false)	// this adds non-null constraint
    public String accessToken;
    
    public String tokenType;

	@Constraints.Required
	public String refreshToken;

	@Constraints.Required
	public long expiresInSeconds;
	
	@Constraints.Required
	@Formats.DateTime(pattern="yyyy-MM-dd")
	public Date expiresDate;

    @ManyToOne
    @JoinColumn(name="user_id", nullable=false)
    public User user;
    
	public void updateFromToken(Token token) {
		accessToken = token.getAccessToken();
		expiresInSeconds = token.getExpiresInSeconds();
		expiresDate = new Date(System.currentTimeMillis() + (token.getExpiresInSeconds() * 1000));
		tokenType = token.getTokenType();
		refreshToken = token.getRefreshToken();
	}
	
    public static Model.Finder<Long,SmartsheetToken> find = new Model.Finder<Long,SmartsheetToken>(Long.class, SmartsheetToken.class);
    
	public static void saveOrUpdate(SmartsheetToken ssToken) {
		if (getById(ssToken.smartsheetTokenId) != null) {
			// update if already exists
			Ebean.update(ssToken);
		} else {
			// create new one if it does not exist
			Ebean.save(ssToken);
		}
	}

	public static SmartsheetToken getById(Long tokenId) {
		if (tokenId != null) {
			SmartsheetToken ssToken = SmartsheetToken.find.byId(tokenId);
			return ssToken;
		} else {
			Logger.warn("SmartsheetToken.getById: the tokenId is null");
		}
		return null;
	}
	
	public static void deleteById(Long tokenId) {
		if (tokenId != null) {
			SmartsheetToken accessToken = SmartsheetToken.find.byId(tokenId);
			if (accessToken != null && accessToken.smartsheetTokenId != null) {
				Ebean.delete(accessToken);
			}
		}
	}
	
	public static Token getTokenFromSmartsheetToken(SmartsheetToken ssToken) {
		Token token = new Token();
		token.setAccessToken(ssToken.accessToken);
		token.setExpiresInSeconds(ssToken.expiresInSeconds);
		token.setRefreshToken(ssToken.refreshToken);
		token.setTokenType(ssToken.tokenType);
		return token;
	}


}

